package com.labichaoka.chaoka.ui.baseinfo.person;

import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.labichaoka.chaoka.BuildConfig;
import com.labichaoka.chaoka.R;
import com.labichaoka.chaoka.base.BaseActivity;
import com.labichaoka.chaoka.base.GlobalParams;
import com.labichaoka.chaoka.entity.FaceAuthRequest;
import com.labichaoka.chaoka.entity.FaceAuthResponse;
import com.labichaoka.chaoka.entity.ProvinceDataPersistModel;
import com.labichaoka.chaoka.entity.SaveInformationRequest;
import com.labichaoka.chaoka.ui.credit.CalculateActivity;
import com.labichaoka.chaoka.utils.DetectionUtil;
import com.labichaoka.chaoka.utils.DialogFactory;
import com.labichaoka.chaoka.utils.SharedPreferencesManager;
import com.labichaoka.chaoka.utils.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.qqtheme.framework.picker.DatePicker;

/*
 * 个人信息-非种子用户
 * */

public class PersonInfoActivity extends BaseActivity implements PersonInfoView ,DialogFactory.SelectAreaDialog.OnSelectAreaListener{
    @BindView(R.id.next1)
    TextView next1;
    @BindView(R.id.next2)
    TextView next2;
    @BindView(R.id.next3)
    TextView next3;
    @BindView(R.id.next4)
    TextView next4;
    @BindView(R.id.next5)
    TextView next5;
    @BindView(R.id.next6)
    TextView next6;
    @BindView(R.id.next7)
    TextView next7;
    @BindView(R.id.next8)
    TextView next8;
    @BindView(R.id.next9)
    TextView next9;
    @BindView(R.id.edu)
    TextView edu;

    @BindView(R.id.graduate_txt)
    TextView graduate_txt;

    @BindView(R.id.work_selected_img)
    ImageView workSelected;
    @BindView(R.id.work_unselected_img)
    ImageView workUnSelected;
    @BindView(R.id.has_work_layout)
    LinearLayout hasWorkLayout;
    @BindView(R.id.has_work_line)
    View lineView;

    @BindView(R.id.save_btn)
    Button submit;
    @BindView(R.id.graduate_school)
    EditText graduateSchool;
    @BindView(R.id.balance)
    EditText balance;
    @BindView(R.id.company_name)
    EditText company_name;
    @BindView(R.id.contact1)
    EditText contact1;
    @BindView(R.id.phone1)
    EditText phone1;
    @BindView(R.id.contact2)
    EditText contact2;
    @BindView(R.id.phone2)
    EditText phone2;
    @BindView(R.id.relation1)
    TextView relation1;
    @BindView(R.id.relation2)
    TextView relation2;
    @BindView(R.id.huoti)
    ImageView huoti;
    @BindView(R.id.home_address)
    TextView home_address;
    @BindView(R.id.home_address_detail)
    EditText home_address_detail;

    @BindView(R.id.industry)
    TextView industry;
    @BindView(R.id.job)
    TextView job;
    @BindView(R.id.merry)
    TextView merry;
    @BindView(R.id.email)
    TextView email;

    private Dialog dialog;
    private List<GlobalParams.Education> list;
    private TextView commonTv;
    private String status;

    private String uniRec, graduateData, uniName, hasWork, company, expectAmount, cname1, cphone1, crelation1, cname2, cphone2, crelation2,liveAddrInfo, liveAddrDetailInfo,provinceCityDistrict;

    private PersonInfoPresenter presenter;

    private ProvinceDataPersistModel provinceData;

    private String industryStr,occupationStr,marriageStr,emailStr;


    private DialogFactory.SelectAreaDialog selectAreaDialog;

    @Override
    protected int initLayoutId() {
        return R.layout.activity_person_info;
    }

    @Override
    protected void initView() {
        next1.setTypeface(iconfont);
        next2.setTypeface(iconfont);
        next3.setTypeface(iconfont);
        next4.setTypeface(iconfont);
        next5.setTypeface(iconfont);
        next6.setTypeface(iconfont);
        next7.setTypeface(iconfont);
        next8.setTypeface(iconfont);
        next9.setTypeface(iconfont);
    }

    @Override
    protected void initData() {
        presenter = new PersonInfoPresenterImpl(this, new PersonInformationInteractorImpl());
        presenter.initProvinceData();
        list = new ArrayList<>();
        dialog = new Dialog(mContext, R.style.Translucent_NoTitle);
        hasWork = "0"; //默认无工作
        hasWorkLayout.setVisibility(View.GONE);
        lineView.setVisibility(View.VISIBLE);
    }


    @OnClick({R.id.edu_layout,
            R.id.graduate_time_layout, R.id.save_btn,R.id.home_address_layout,
            R.id.relation1_layout, R.id.relation2_layout, R.id.work_selected_layout, R.id.work_unselected_layout, R.id.huoti
            ,R.id.industry_layout,R.id.job_layout,R.id.merry_layout,R.id.email_layout
    })
    public void click(View v) {
        switch (v.getId()) {
            case R.id.edu_layout:
                commonTv = edu;
                initDialogData(0, "教育程度");
                break;
            case R.id.huoti:
                FaceAuthRequest request = new FaceAuthRequest();
                request.setCallBankUrl(BuildConfig.WEB_HOST+"blankPage");
                presenter.faceAuth(request);

                break;
            case R.id.home_address_layout:
                showAddressPick();
                break;

            case R.id.graduate_time_layout:
                onYearMonthPicker();
                break;
            case R.id.save_btn:
                saveInformation();
                break;
            case R.id.relation1_layout:
                commonTv = relation1;
                initDialogData(3, "与本人关系");
                break;
            case R.id.relation2_layout:
                commonTv = relation2;
                initDialogData(4, "与本人关系");
                break;
            case R.id.work_selected_layout:
                workSelected.setImageResource(R.mipmap.work_selected);
                workUnSelected.setImageResource(R.mipmap.work_unselected);
                hasWork = "1";
                hasWorkLayout.setVisibility(View.VISIBLE);
                lineView.setVisibility(View.VISIBLE);
                checkButtonState();
                break;
            case R.id.work_unselected_layout:
                workSelected.setImageResource(R.mipmap.work_unselected);
                workUnSelected.setImageResource(R.mipmap.work_selected);
                hasWork = "0";
                company="";
                company_name.setText("");
                company_name.setTextColor(getResources().getColor(R.color.font_909090));
                hasWorkLayout.setVisibility(View.GONE);
                lineView.setVisibility(View.GONE);
                checkButtonState();
                break;
            case R.id.industry_layout:
                commonTv = industry;
                initDialogData(1, "所从事行业");
                break;
            case R.id.job_layout:
                commonTv = job;
                initDialogData(2, "职业");
                break;
            case R.id.merry_layout:
                commonTv = merry;
                initDialogData(5, "婚姻状况");
                break;
            case R.id.email_layout:
                Bundle bundle=new Bundle();
                bundle.putString("email",emailStr);
                gotoActivity(mContext,EmailActivity.class,bundle);
                break;
        }

    }

    public void showAddressPick(){
        if (selectAreaDialog == null) {
            selectAreaDialog = DialogFactory.createSelectAreaDialog(this, provinceData);
            selectAreaDialog.show();
            selectAreaDialog.setOnSelectAreaListener(this);
        }else{
            selectAreaDialog.show();
        }
    }


    private void saveInformation() {
        if (checkValue()) {
            SaveInformationRequest request = new SaveInformationRequest();
            request.setCname1(cname1);
            request.setCname2(cname2);
            request.setCompany(company);
            request.setCphone1(cphone1);
            request.setCrelation1(crelation1);
            request.setCphone2(cphone2);
            request.setCrelation2(crelation2);
            request.setExpectAmount(expectAmount);
            request.setGraduateData(graduateData);
            request.setHasWork(hasWork);
            request.setUniName(uniName);
            request.setUniRec(uniRec);
            request.setLiveAddrDetailInfo(liveAddrDetailInfo);
            request.setLiveAddrInfo(liveAddrInfo);
            request.setProvinceCityDistrict(provinceCityDistrict);
            request.setIndustry(industryStr);
            request.setEmail(emailStr);
            request.setMarriage(marriageStr);
            request.setOccupation(occupationStr);
            presenter.saveInformation(request);

            presenter.behavior(GlobalParams.SUB_USERINFO);
        }

    }

    private boolean checkValue() {
        String phone = SharedPreferencesManager.getInstance().getString("phone", "");
        if (!DetectionUtil.isMobileNO(cphone1) || !DetectionUtil.isMobileNO(cphone2)) {
            ToastUtils.show("请输入正确的手机号!");
            return false;
        } else if (cphone1.equals(cphone2)) {
            ToastUtils.show("联系人手机号不能相同!");
            return false;
        } else if (phone.equals(cphone1) || phone.equals(cphone2)) {
            ToastUtils.show("联系人手机号不能和登录手机号相同!");
            return false;
        }else if(!DetectionUtil.isEmail(emailStr)){
            ToastUtils.show("邮箱格式错误，请重新输入!");
            return false;
        }
        return true;
    }

    public void onYearMonthPicker() {
        DatePicker picker = new DatePicker(this, DatePicker.YEAR_MONTH);
        picker.setWidth(picker.getScreenWidthPixels());
        picker.setRangeStart(2008, 1, 14);
        picker.setRangeEnd(2018, 12, 11);
        picker.setSelectedItem(2010, 1);
        picker.setTopLineColor(getResources().getColor(R.color.divide_f4f4f4));
        picker.setLabelTextColor(0x00000000);
        picker.setDividerColor(getResources().getColor(R.color.divide_f4f4f4));
        picker.setSubmitTextColor(getResources().getColor(R.color.mainColor));
        picker.setCancelTextColor(getResources().getColor(R.color.mainColor));
        picker.setTextSize(14);
        picker.setTitleText("请选择日期");
        picker.setTitleTextSize(15);
        picker.setTitleTextColor(getResources().getColor(R.color.mainColor));
        picker.setContentPadding(15, 15);
        picker.setTextColor(getResources().getColor(R.color.mainColor), getResources().getColor(R.color.font_909090));
        picker.setOnDatePickListener((DatePicker.OnYearMonthPickListener) (year, month) -> {
            graduateData = year + "-" + month;
            graduate_txt.setText(year + "-" + month);
            graduate_txt.setTextColor(getResources().getColor(R.color.font_3a3a38));
            checkButtonState();
        });
        picker.show();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        EventBus.getDefault().register(this);

        graduateSchool.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                uniName = s.toString().trim();
                checkButtonState();
            }
        });

        balance.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                expectAmount = s.toString().trim();
                checkButtonState();
            }
        });

        company_name.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                company = s.toString().trim();
                checkButtonState();
            }
        });
        contact1.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                cname1 = s.toString().trim();
                checkButtonState();
            }
        });

        phone1.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                cphone1 = s.toString().trim();
                checkButtonState();
            }
        });

        contact2.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                cname2 = s.toString().trim();
                checkButtonState();
            }
        });

        phone2.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                cphone2 = s.toString().trim();
                checkButtonState();
            }
        });

        home_address_detail.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                liveAddrDetailInfo=s.toString().trim();
                checkButtonState();
            }
        });


    }

    public void showBottomDialog(int type, String titleStr) {
        final LayoutInflater inflater = LayoutInflater.from(mContext);
        View v = inflater.inflate(R.layout.person_info_dialog, null);
        dialog.setContentView(v, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        Window window = dialog.getWindow();
        window.setGravity(Gravity.BOTTOM);
        window.setWindowAnimations(R.style.showdialog);
        TextView close_icon = v.findViewById(R.id.close);
        TextView title = v.findViewById(R.id.title);
        RecyclerView recyclerView = v.findViewById(R.id.rv_list);
        recyclerView.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        //添加自定义分割线
        DividerItemDecoration divider = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL);
        divider.setDrawable(ContextCompat.getDrawable(this, R.drawable.divide_drawable));
        recyclerView.addItemDecoration(divider);

        title.setText(titleStr);
        close_icon.setTypeface(iconfont);
        close_icon.setOnClickListener((view) -> {
            dialog.dismiss();
        });


        PersonInfoAdapter adapter = new PersonInfoAdapter(mContext, list);
        recyclerView.setAdapter(adapter);

        adapter.setOnItemClickListener((position -> {
            dialog.dismiss();
            setValue(type, position);
        }));

        WindowManager.LayoutParams wl = window.getAttributes();
        wl.x = 0;
        wl.width = ViewGroup.LayoutParams.MATCH_PARENT;
        wl.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        dialog.onWindowAttributesChanged(wl);
        dialog.setCanceledOnTouchOutside(true);

        dialog.show();

    }

    public void initDialogData(int type, String titleStr) {
        switch (type) {
            case 0:
                list = GlobalParams.getEducation();
                break;
            case 3:
                list = GlobalParams.getRelation();
                break;
            case 4:
                list = GlobalParams.getRelation();
                break;
            case 1:
                list = GlobalParams.getIndustry();
                break;
            case 2:
                list = GlobalParams.getJob();
                break;
            case 5:
                list = GlobalParams.getMerry();
                break;
        }

        showBottomDialog(type, titleStr);
    }

    public void setValue(int type, int pos) {
        //设置提交的value
        switch (type) {
            case 0:
                //教育程度
                uniRec = list.get(pos).getId();
                break;
            case 3:
                //关系1
                crelation1 = list.get(pos).getId();
                break;
            case 4:
                //关系2
                crelation2 = list.get(pos).getId();
                break;
            case 1:
                //行业信息
                industryStr = list.get(pos).getId();
                break;
            case 2:
                //职业信息
                occupationStr = list.get(pos).getId();
                break;
            case 5:
                //婚姻
                marriageStr = list.get(pos).getId();
                break;
        }
        checkButtonState();

        commonTv.setText(list.get(pos).getValue());
        commonTv.setTextColor(getResources().getColor(R.color.font_3a3a38));
    }

    @Override
    public void showProgress() {
        showLoadingProgress();
    }

    @Override
    public void hideProgress() {
        hideLoadingProgress();
    }

    @Override
    public void showMessage(String str) {
        ToastUtils.show(str);
    }

    @Override
    public void toNext() {
        gotoActivity(mContext, CalculateActivity.class,null);
        finish();
    }

    @Override
    public void faceAuthCallback(FaceAuthResponse response) {
        presenter.behavior(GlobalParams.CLICK_FACE_RECOGNITION);
        if (response.getData() == null) {
            ToastUtils.show("获取数据异常，请稍后重试！");
            return;
        }

        String data = response.getData();
        Bundle bundle = new Bundle();
        bundle.putString("url", data);
        gotoActivity(mContext,FaceActivity.class,bundle);
    }

    @Override
    public void getFaceAuthStatus(FaceAuthResponse response) {
        status=response.getData();
        if (TextUtils.isEmpty(status)){
            return;
        }

        switch (status){
            case "1":
                huoti.setImageResource(R.mipmap.huoti3);
                huoti.setEnabled(false);
                break;
            case "2":
                huoti.setEnabled(false);
                huoti.setImageResource(R.mipmap.huoti2);
                break;
            case "3":
                huoti.setEnabled(true);
                huoti.setImageResource(R.mipmap.huoti);
                break;
        }
        checkButtonState();
    }

    @Override
    public void initProvince(ProvinceDataPersistModel p) {
        provinceData=p;
    }


    public void checkButtonState() {
        if (!TextUtils.isEmpty(hasWork) && hasWork.equals("1")) {
            //有工作
            if (TextUtils.isEmpty(uniRec) || TextUtils.isEmpty(graduateData) ||
                    TextUtils.isEmpty(uniName) || TextUtils.isEmpty(hasWork) ||
                    TextUtils.isEmpty(company) || TextUtils.isEmpty(expectAmount) ||
                    TextUtils.isEmpty(cname1) || TextUtils.isEmpty(cphone1) ||
                    TextUtils.isEmpty(crelation1) || TextUtils.isEmpty(cname2) ||
                    TextUtils.isEmpty(cphone2) || TextUtils.isEmpty(crelation2)||
                    TextUtils.isEmpty(provinceCityDistrict)||TextUtils.isEmpty(liveAddrInfo)||
                    TextUtils.isEmpty(liveAddrDetailInfo)||TextUtils.isEmpty(industryStr)||
                    status.equals("3")||TextUtils.isEmpty(occupationStr)||
                    TextUtils.isEmpty(marriageStr)||TextUtils.isEmpty(emailStr)
                    ) {
                submit.setEnabled(false);
            } else {
                submit.setEnabled(true);
            }
        } else {
            if (TextUtils.isEmpty(uniRec) || TextUtils.isEmpty(graduateData) ||
                    TextUtils.isEmpty(uniName) || TextUtils.isEmpty(hasWork) ||
                    TextUtils.isEmpty(expectAmount) || TextUtils.isEmpty(cname1) ||
                    TextUtils.isEmpty(cphone1) || TextUtils.isEmpty(crelation1) ||
                    TextUtils.isEmpty(cname2) || TextUtils.isEmpty(cphone2) ||
                    TextUtils.isEmpty(crelation2)||
                    TextUtils.isEmpty(provinceCityDistrict)||TextUtils.isEmpty(liveAddrInfo)||
                    TextUtils.isEmpty(liveAddrDetailInfo)||TextUtils.isEmpty(industryStr)||
                    status.equals("3")||TextUtils.isEmpty(occupationStr)||
                    TextUtils.isEmpty(marriageStr)||TextUtils.isEmpty(emailStr)
                    ) {
                submit.setEnabled(false);
            } else {
                submit.setEnabled(true);
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        presenter.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        presenter.getFaceAuthStatus();
    }

    @Override
    public void onSelect(String addr, String zipCode, String id) {
        liveAddrInfo=id;
        home_address.setText(addr);
        provinceCityDistrict=addr;
        home_address.setTextColor(getResources().getColor(R.color.font_3a3a38));
        checkButtonState();
    }

    @Subscribe
    public void getEventBus(String str){
        if (!TextUtils.isEmpty(str)){
            email.setText(str);
            email.setTextColor(getResources().getColor(R.color.font_3a3a38));
            emailStr=str;
        }else{
            ToastUtils.show("获取邮箱错误");
        }

    }
}
